<template>
  <div class="list-table">
    <div class="form-flex">
      <div class="area-header">
        <span class="area-header-title">董事会席位信息</span>
      </div>
      <template v-for="(form, index) in shareholdersList">
        <div :key="index" class="flex">
          <div class="el-form-item">
            <label class="el-form-item__label">股东</label>
            <div class="el-form-item__content">{{ form.investorName }}</div>
          </div>
          <div class="el-form-item">
            <label class="el-form-item__label">席位</label>
            <div class="el-form-item__content">{{ form.supervisoryBoardSeatCount }}</div>
          </div>
          <div class="el-form-item">
            <label class="el-form-item__label">职务类型</label>
            <div class="el-form-item__content">{{ form.supervisorPositionTypeListName }}</div>
          </div>
        </div>
      </template>
    </div>

    <div class="form-flex">
      <div class="area-header">
        <span />
        <span>
          <el-button size="mini" @click="seeVEOI">{{ $t("查看外部批披露信息") }}</el-button>
          <el-button size="mini" @click="downloadHandler">{{ $t("董监事各席位的任职信息下载") }}</el-button>
        </span>
      </div>
      <div class="area-header" style="margin-bottom:0px;">
        <span v-if="batchFlag" style="color:red;">董事会当前界次任职期限:{{ parseTime(validateForm.startDate) }} - {{ parseTime(validateForm.endDate) }} </span>
        <span v-else>
          <!-- class="dataForm" -->
          <el-form ref="dateForm" v-loading="loading" inline="true" :model="validateForm" label-width="120px">
            <el-row>
              <el-col :span="11">
                <DatePicker v-model="validateForm.startDate" size="mini" placeholder="任职开始时间" @change="changeDateStart" />
              </el-col>
              <el-col :span="2"><div style=" text-align:center;line-height: normal;">-</div></el-col>
              <el-col :span="11">
                <DatePicker v-model="validateForm.endDate" size="mini" placeholder="任职结束时间" @change="changeDateEnd" />
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span>
          <template v-if="batchFlag">
            <el-button size="mini" @click="batchAddHandler">{{ $t("批量录入下一任期信息") }}</el-button>
          </template>
          <template v-else>
            <el-button size="mini" @click="cancelHandle">{{ $t("取消") }}</el-button>
            <el-button size="mini" @click="addHandler">{{ $t("新增席位") }}</el-button>
            <el-button size="mini" @click="batchSaveHandler">{{ $t("批量保存") }}</el-button>
          </template>
        </span>
      </div>

    </div>

    <el-form ref="form" v-loading="loading" :model="validateForm" label-width="120px" class="dataForm">
      <div v-for="(form, index) in validateForm.forms" :key="index" class="form-flex">
        <div class="area-header">
          <span class="area-header-title">
            董事会席位{{ index + 1 }} {{ form.shareholder }}
            <el-radio-group v-model="form.incumbentType" style="margin-left: 20px;">
              <el-radio v-for="(item) in incumbentTypeOption" :key="item.dictValue" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
            </el-radio-group>
          </span>
          <span>
            <el-button v-if="batchFlag && !editOrSaveFlag" size="mini" @click="nextHandler(index);nextFlag=!nextFlag">{{ nextFlag? $t("保存下一任期信息"):$t("录入下一任期信息") }}</el-button>
            <el-button v-if="batchFlag && !nextFlag" size="mini" @click="updateHandler(form,index);editOrSaveFlag=!editOrSaveFlag"> {{ editOrSaveFlag? $t("保存当前人员"):$t("修改当前人员") }}</el-button>
            <el-button v-if="batchFlag" size="mini" @click="recordHandler(index)">{{ $t("该席位的以往人员信息") }}</el-button>
            <el-button v-if="!batchFlag" size="mini" @click="deleteHandler(index)">{{ $t("删除") }}</el-button>
          </span>
        </div>
        <div class="flex">
          <el-form-item :label="$t('派出股东方')" :prop="'forms.' + index + '.bodSo'" :rules="rules.bodSo">
            <div v-if="!form.isEdit" class="field">{{ form.bodSoName }}</div>
            <el-select v-else v-model="form.bodSo" size="mini" placeholder="派出股东方" @change="bodHandler(form.bodSo,index)">
              <el-option v-for="dict in holderOption" :key="dict.id" :label="$t(dict.investor)" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('我方董事/外方董事')" :prop="'forms.' + index + '.chairmanType'" :rules="rules.chairmanType">
            <div v-if="!form.isEdit" class="field">{{ form.chairmanTypeLabel }}</div>
            <el-select v-else v-model="form.chairmanType" size="mini" placeholder="" @change="chairHandler(form.chairmanType,index)">
              <el-option v-for="dict in dsBodTypeOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('内部董事/外部董事')" :prop="'forms.' + index + '.chairmanTypeInterior'" :rules="rules.chairmanTypeInterior">
            <div v-if="!form.isEdit" class="field">{{ form.chairmanTypeInteriorLabel }}</div>
            <el-select v-else v-model="form.chairmanTypeInterior" size="mini" placeholder="">
              <el-option v-for="dict in dsBodTypeOption2" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('姓名')" :prop="'forms.' + index + '.bodName'" :rules="rules.bodName">
            <div v-if="form.isEdit === false">
              <div> {{ form.dsName }}</div>
            </div>
            <div v-else class="field left-right">
              <el-select v-model="form.bodName" size="mini" placeholder="姓名" style="width: 90%;" clearable @change="bodNameChange(index)">
                <el-option v-for="dict in bodNameOption" :key="dict.id" :label="$t(dict.dsName)" :value="dict.id" />
              </el-select>
              <div>
                <el-button type="text" style="margin-left: 10px;" @click="addBodHandler(form,index)">{{ $t("添加") }}</el-button>
              </div>
            </div>

          </el-form-item>
          <el-form-item :label="$t('职务')" :prop="'forms.' + index + '.duty'" :rules="rules.duty">
            <div v-if="!form.isEdit" class="field">{{ form.dutyLabel }}</div>
            <el-select v-else v-model="form.duty" size="mini" placeholder="">
              <el-option v-for="dict in dsZwOption" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('是否专职')" :prop="'forms.' + index + '.isFullTime'" :rules="rules.isFullTime">
            <div v-if="!form.isEdit" class="field">{{ form.isFullTimeLabel }}</div>
            <dictSelect v-else v-model="form.isFullTime" dictionary="sys_yes_no" size="mini" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('身份证号')" :prop="'forms.' + index + '.idCard'" :rules="rules.idCard">
            <div v-if="form.isEdit === false" class="field">{{ form.idCard }}</div>
            <el-input v-else v-model="form.idCard" size="mini" placeholder="身份证号" />
          </el-form-item>
          <el-form-item :label="$t('性别')" :prop="'forms.' + index + '.gender'" :rules="rules.gender">
            <div v-if="!form.isEdit" class="field">{{ form.genderLabel }}</div>
            <dictSelect v-else v-model="form.gender" dictionary="sys_user_sex" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('手机号')" :prop="'forms.' + index + '.phone'" :rules="rules.phone">
            <div v-if="form.isEdit === false" class="field">{{ form.phone }}</div>
            <el-input v-else v-model="form.phone" size="mini" placeholder="手机号" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('任职时间(开始)')" :prop="'forms.' + index + '.startDate'" :rules="rules.startDate">
            <div v-if="form.isEdit === false" class="field">{{ parseTime(form.startDate) }}</div>
            <DatePicker v-else v-model="form.startDate" size="mini" placeholder="" />
          </el-form-item>
          <el-form-item :label="$t('任职时间(结束)')" :prop="'forms.' + index + '.endDate'" :rules="rules.endDate">
            <div v-if="form.isEdit === false" class="field">{{ parseTime(form.endDate) }}</div>
            <DatePicker v-else v-model="form.endDate" size="mini" placeholder="" />
          </el-form-item>
          <el-form-item :label="$t('个人简历')" :prop="'forms.' + index + '.resumeId'" :rules="rules.resumeId">
            <div class="field left-right">
              <template v-if="form.isEdit === false">
                <div class="pre link-type" :title="form.resumeName" @click="onlinePreview(form.resumeId)">{{ form.resumeName }}</div>
                <span class="el-icon-bottom link-type" @click="downloadFileById(form.resumeId)" />
              </template>
              <template v-else>
                <div> {{ form.resumeName }}</div>
                <uploadSingle
                  ref="uploadSingle"
                  :data-type="'deal_financing_lending'"
                  :data-table-row-num="index"
                  :upload-btn-name="$t('上传')"
                  @onFileSuccess="handleResumeIdFileSuccess"
                />
              </template>
            </div>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item :label="$t('预计退休时间')" :prop="'forms.' + index + '.projectedRetirementDate'" :rules="rules.projectedRetirementDate">
            <div v-if="form.isEdit === false" class="field">{{ parseTime(form.projectedRetirementDate) }}</div>
            <DatePicker v-else v-model="form.projectedRetirementDate" size="mini" placeholder="预计退休时间" :picker-options="pickerOptions" @change="handleDateChange(index)" />
          </el-form-item>
          <el-form-item :label="$t('距离退休时间')">
            <div class="field">{{ calculateTimeDifference(form.projectedRetirementDate) }}</div>
          </el-form-item>
          <el-form-item label="" prop="" />
        </div>
        <div class="flex">
          <el-form-item :label="$t('党政职务')" prop="partyPosition">
            <el-checkbox-group v-if="form.isEdit" v-model="form.partyPositionList">
              <el-checkbox v-for="(option, index) in dsDwzwOption" :key="index" :label="option.dictValue">{{ option.dictLabel }}</el-checkbox>
            </el-checkbox-group>
            <el-checkbox-group v-else v-model="form.partyPositionList">
              <el-checkbox v-for="(option, index) in dsDwzwOption" :key="index" :label="option.dictValue" disabled>{{ option.dictLabel }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <template v-if="form.incumbentType != 'jp'">
          <div class="area-header">
            <span class="area-header-title">聘任相关</span>
          </div>
          <div class="flex">
            <el-form-item :label="$t('党委会研究讨论届次/党委发文文号')" :prop="'forms.' + index + '.documentText'" :rules="rules.documentText">
              <div v-if="form.isEdit === false" class="field">{{ form.documentText }}</div>
              <el-input v-else v-model="form.documentText" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item :label="$t('距离退组织部任免单时间休时间')" :prop="'forms.' + index + '.effectiveDate'" :rules="rules.effectiveDate">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.effectiveDate) }}</div>
              <DatePicker v-else v-model="form.effectiveDate" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item :label="$t('股东推荐决策程序')" :prop="'forms.' + index + '.srdp'" :rules="rules.srdp">
              <div v-if="form.isEdit === false" class="field">{{ form.srdp }}</div>
              <el-input v-else v-model="form.srdp" size="mini" placeholder="" />
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item :label="$t('股东任命文件')" :prop="'forms.' + index + '.sdpFileId'" :rules="rules.sdpFileId">
              <div class="field left-right">
                <template v-if="form.isEdit === false">
                  <div class="pre link-type" :title="form.sdpFileName" @click="onlinePreview(form.sdpFileId)">{{ form.sdpFileName }}</div>
                  <span class="el-icon-bottom link-type" @click="downloadFileById(form.sdpFileId)" />
                </template>
                <template v-else>
                  <div> {{ form.sdpFileName }}</div>
                  <uploadSingle
                    ref="uploadSingle"
                    :data-type="'deal_financing_lending'"
                    :data-table-row-num="index"
                    :upload-btn-name="$t('上传')"
                    @onFileSuccess="handleSuccess"
                  />
                </template>
              </div>
            </el-form-item>
            <el-form-item :label="$t('股东任命文件时间')" :prop="'forms.' + index + '.sdpTime'" :rules="rules.sdpTime">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.sdpTime) }}</div>
              <DatePicker v-else v-model="form.sdpTime" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item label="" prop="" />
          </div>
          <div class="flex">
            <el-form-item :label="$t('公司任命文件')" :prop="'forms.' + index + '.cdaFileId'" :rules="rules.cdaFileId">
              <div class="field left-right">
                <template v-if="form.isEdit === false">
                  <div class="pre link-type" :title="form.cdaFileName" @click="onlinePreview(form.cdaFileId)">{{ form.cdaFileName }}</div>
                  <span class="el-icon-bottom link-type" @click="downloadFileById(form.cdaFileId)" />
                </template>
                <template v-else>
                  <div> {{ form.cdaFileName }}</div>
                  <uploadSingle
                    ref="uploadSingle"
                    :data-type="'deal_financing_lending'"
                    :data-table-row-num="index"
                    :upload-btn-name="$t('上传')"
                    @onFileSuccess="handleCdaFileSuccess"
                  />
                </template>
              </div>
            </el-form-item>
            <el-form-item :label="$t('公司任命文件时间')" :prop="'forms.' + index + '.cdaTime'" :rules="rules.cdaTime">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.cdaTime) }}</div>
              <DatePicker v-else v-model="form.cdaTime" size="mini" placeholder="取得时间" />
            </el-form-item>
            <el-form-item label="" prop="" />
          </div>
        </template>
        <template v-if=" form.incumbentType == 'jp'">
          <div class="area-header">
            <span class="area-header-title">解聘相关</span>
          </div>
          <div class="flex">
            <el-form-item :label="$t('党委会研究讨论届次/党委发文文号')" :prop="'forms.' + index + '.documentText'" :rules="rules.documentText">
              <div v-if="form.isEdit === false" class="field">{{ form.documentText }}</div>
              <el-input v-else v-model="form.documentText" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item :label="$t('距离退组织部任免单时间休时间')" :prop="'forms.' + index + '.effectiveDate'" :rules="rules.effectiveDate">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.effectiveDate) }}</div>
              <DatePicker v-else v-model="form.effectiveDate" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item :label="$t('股东推荐决策程序')" :prop="'forms.' + index + '.srdp'" :rules="rules.srdp">
              <div v-if="form.isEdit === false" class="field">{{ form.srdp }}</div>
              <el-input v-else v-model="form.srdp" size="mini" placeholder="" />
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item :label="$t('股东任命文件')" :prop="'forms.' + index + '.layoffSdpFileId'" :rules="rules.layoffSdpFileId">
              <div class="field left-right">
                <template v-if="form.isEdit === false">
                  <div class="pre" @click="onlinePreview(form.layoffSdpFileId)">
                    {{ form.layoffSdpFileName }}
                  </div>
                  <el-button type="text" @click="downloadFileById(form.layoffSdpFileId)">{{ $t("下载") }}</el-button>
                </template>
                <template v-else>
                  <div> {{ form.layoffSdpFileName }}</div>
                  <uploadSingle
                    ref="uploadSingle"
                    :data-type="'deal_financing_lending'"
                    upload-style="color: #409EFF;cursor: pointer;border: 0px;"
                    :data-table-row-num="index"
                    :upload-btn-name="$t('上传')"
                    @onFileSuccess="handlelayoffSdpFileSuccess"
                  />
                </template>
              </div>
            </el-form-item>
            <el-form-item :label="$t('股东任命文件时间')" :prop="'forms.' + index + '.sdpTime'" :rules="rules.sdpTime">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.sdpTime) }}</div>
              <DatePicker v-else v-model="form.sdpTime" size="mini" placeholder="" />
            </el-form-item>
            <el-form-item label="" prop="" />
          </div>
          <div class="flex">
            <el-form-item :label="$t('公司任命文件')" :prop="'forms.' + index + '.layoffCdaFileId'" :rules="rules.layoffCdaFileId">
              <div class="field left-right">
                <template v-if="form.isEdit === false">
                  <div class="pre" @click="onlinePreview(form.layoffCdaFileId)">
                    {{ form.layoffCdaFileName }}
                  </div>
                  <el-button type="text" @click="downloadFileById(form.layoffCdaFileId)">{{ $t("下载") }}</el-button>
                </template>
                <template v-else>
                  <div> {{ form.layoffCdaFileName }}</div>
                  <uploadSingle
                    ref="uploadSingle"
                    :data-type="'deal_financing_lending'"
                    upload-style="color: #409EFF;cursor: pointer;border: 0px;"
                    :data-table-row-num="index"
                    :upload-btn-name="$t('上传')"
                    @onFileSuccess="handlelayoffCdaFileIdFileSuccess"
                  />
                </template>
              </div>
            </el-form-item>
            <el-form-item :label="$t('公司任命文件时间')" :prop="'forms.' + index + '.cdaTime'" :rules="rules.cdaTime">
              <div v-if="form.isEdit === false" class="field">{{ parseTime(form.cdaTime) }}</div>
              <DatePicker v-else v-model="form.cdaTime" size="mini" placeholder="取得时间" />
            </el-form-item>
            <el-form-item label="" prop="" />
          </div>
        </template>
      </div>
    </el-form>
    <el-dialog title="董监高" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dsSeniorManagerForm ref="dsSeniorManagerForm" :is-show-list="false" />
    </el-dialog>
    <el-dialog
      title="席位的以往人员信息"
      :visible.sync="seatFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <el-table
        v-loading="seatLoading"
        :data="dsDataList"
        height="500px"
        style="width: 100%"
      >
        <el-table-column prop="date" label="任职期限">
          <template slot-scope="scope">
            {{ parseTime(scope.row.startDateName) }} -  {{ parseTime(scope.row.endDateName) }}
          </template>
        </el-table-column>
        <el-table-column prop="dsName" label="姓名" />
        <el-table-column prop="zwName" label="职务" />

      </el-table>
    </el-dialog>

    <el-dialog
      title="外部批披露信息"
      :visible.sync="VEOIFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <el-table
        v-loading="VEOILoading"
        :data="VEOIDataList"
        height="500px"
        style="width: 100%"
      >
        <el-table-column prop="staffName" label="姓名" />
        <el-table-column prop="postType" label="职务">
          <template slot-scope="scope">
            {{ toUpperCaseAndJoin(scope.row.postType) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import config from '@/utils/config'
import { getToken } from '@/utils/auth'
import {
  findListByCompanyId,
  queryShareholdersWithBoardSeats
} from '@/api/fund/ds/dsShareHolder'
import {
  listByCompanyId,
  saveDsBod,
  batchSaveBod,
  findDsBySeatIndex,
  saveNextDsBod,
  findVEOI
} from '@/api/fund/ds/dsBod'
import {
  dsListByCompanyId
} from '@/api/fund/ds/dsSeniorManager'
import dsSeniorManagerForm from '../seniorManager/dsSeniorManagerForm'
import uploadSingle from '@/components/File/Upload/single.vue'

export default {
  components: {
    dsSeniorManagerForm,
    uploadSingle
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const today = new Date()
          const currentTime = today.getTime()
          const dateTime = time.getTime()
          return dateTime < currentTime
        }
      },
      VEOIFormOpen: false,
      VEOILoading: false,
      editOrSaveFlag: false,
      nextFlag: false,
      batchFlag: true,
      formOpen: false,
      seatFormOpen: false,
      seatLoading: false,
      loading: false,
      recordIndex: 0,
      companyId: this.$route.query.companyId,
      shareholdersList: [],
      dsDataList: [],
      VEOIDataList: [],
      cacheForms: [],
      bodNameOption: [],
      holderOption: [],
      incumbentTypeOption: [],
      dsBodTypeOption: [],
      dsBodTypeOption2: [],
      bodSoOption: [],
      dsZwOption: [],
      dsDwzwOption: [],
      validateForm: {
        id: undefined,
        startDate: undefined,
        endDate: undefined,
        forms: []
      },
      rules: {
        bodSo: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        chairmanType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        chairmanTypeInterior: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        bodName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        duty: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        isFullTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        idCard: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        gender: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        phone: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        startDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        endDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        resumeId: [{ required: true, message: this.$t('请上传文件'), trigger: 'blur' }],
        projectedRetirementDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        documentText: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        effectiveDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        srdp: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        sdpFileId: [{ required: true, message: this.$t('请上传文件'), trigger: 'blur' }],
        sdpTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        cdaFileId: [{ required: true, message: this.$t('请上传文件'), trigger: 'blur' }],
        cdaTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        layoffSdpFileId: [{ required: true, message: this.$t('请上传文件'), trigger: 'blur' }],
        layoffCdaFileId: [{ required: true, message: this.$t('请上传文件'), trigger: 'blur' }]
      },

      sdpFileIdFileList: []

    }
  },
  created() {
    this.getList()
    this.initDict()
    this.getShareholdersList()
  },
  methods: {
    initDict() {
      this.getDicts('ds_lrlx').then(response => {
        this.incumbentTypeOption = response.data
      })
      this.getDicts('ds_bod_type').then(response => {
        this.dsBodTypeOption = response.data
      })
      this.getDicts('ds_bod_type2').then(response => {
        this.dsBodTypeOption2 = response.data
      })
      this.getDicts('ds_zw').then(response => {
        this.dsZwOption = response.data
      })
      this.getDicts('ds_dwzw').then(response => {
        this.dsDwzwOption = response.data
      })
      const queryParam = {
        companyId: this.companyId
      }
      findListByCompanyId(queryParam).then(res => {
        this.holderOption = res.data
      })
      dsListByCompanyId(queryParam).then(res => {
        this.bodNameOption = res.data
      })
    },
    updateHandler(form, index) {
      const editFlag = !form.isEdit
      if (editFlag) {
        this.$set(this.validateForm.forms[index], 'isEdit', editFlag)
        this.$forceUpdate()
        return
      }
      if (!editFlag) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            const row = this.validateForm.forms[index]
            row.partyPosition = row.partyPositionList ? row.partyPositionList.toString() : ''
            saveDsBod(row).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            this.locationError(document)
          }
        }).catch(() => {
          this.loading = false
        })
      }
    },
    getList() {
      this.loading = true
      const queryParam = {
        companyId: this.companyId,
        isRecord: '0'
      }
      listByCompanyId(queryParam).then(res => {
        this.validateForm.forms = res.data.dsBodList
        this.validateForm.id = res.data.id
        this.validateForm.startDate = res.data.startDate
        this.validateForm.endDate = res.data.endDate
        this.validateForm.forms.map(item => {
          item.isEdit = false
        })
        this.loading = false
      })
    },
    bodHandler(val, index) {
      const foundObject = this.holderOption.find(object => object.id === val)
      this.$set(this.validateForm.forms[index], 'chairmanType', undefined)
      this.$set(this.validateForm.forms[index], 'chairmanTypeInterior', undefined)
      if (foundObject && foundObject.investorCategory === '外方') {
        this.$set(this.validateForm.forms[index], 'chairmanType', 'wfds')
        this.$set(this.validateForm.forms[index], 'chairmanTypeInterior', 'wbds')
      }
    },
    chairHandler(val, index) {
      this.$set(this.validateForm.forms[index], 'duty', undefined)
      if (val === 'zgds') {
        this.$set(this.validateForm.forms[index], 'duty', 'zgds')
      }
    },
    addBodHandler(form, index) {
      this.formOpen = true
      this.recordIndex = index
    },
    assignSeniorManagerHandler(form) {
      const queryParam = {
        companyId: this.companyId
      }
      dsListByCompanyId(queryParam).then(res => {
        this.bodNameOption = res.data
        this.$set(this.validateForm.forms[this.recordIndex], 'bodName', form.id)
        this.$set(this.validateForm.forms[this.recordIndex], 'idCard', form.idNumber)
        this.$set(this.validateForm.forms[this.recordIndex], 'gender', form.gender)
        this.$set(this.validateForm.forms[this.recordIndex], 'phone', form.phone)
        this.$set(this.validateForm.forms[this.recordIndex], 'projectedRetirementDate', form.estimatedRetirementDate)
        this.$forceUpdate()
      })
    },
    handleDateChange(index) {
      var timeDifference = this.calculateTimeDifference(this.validateForm.forms[index].projectedRetirementDate)
      this.$set(this.validateForm.forms[index], 'timeToRetirement', timeDifference)
      this.$forceUpdate()
    },
    calculateTimeDifference(inputDate) {
      if (!inputDate) {
        return ''
      }
      var targetDate = new Date(inputDate)
      var currentDate = new Date()
      var timeDifference = targetDate - currentDate
      var millisecondsInYear = 1000 * 60 * 60 * 24 * 365
      var years = Math.floor(timeDifference / millisecondsInYear)
      var remainingMilliseconds = timeDifference % millisecondsInYear
      var months = Math.floor(remainingMilliseconds / (1000 * 60 * 60 * 24 * 30))
      var result = ''
      if (years === 0) {
        result = (months + 1) + '个月'
      } else {
        result = years + '年' + (months + 1) + '个月'
      }
      return result
    },
    nextHandler(index) {
      if (this.nextFlag) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            const row = this.validateForm.forms[index]
            row['bodDateId'] = this.validateForm.id
            row['seatIndex'] = index + 1
            row['companyId'] = this.companyId
            saveNextDsBod(row).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            this.locationError(document)
          }
        }).catch(() => {
          this.loading = false
        })
      } else {
        const keys = Object.keys(this.validateForm.forms[index])
        this.$set(this.validateForm.forms[index], 'isEdit', true)
        for (const key of keys) {
          if (key !== 'isEdit') {
            if (key === 'partyPositionList') {
              this.$set(this.validateForm.forms[index], key, [])
            } else {
              this.$set(this.validateForm.forms[index], key, undefined)
            }
          }
        }
      }
      this.$forceUpdate()
    },
    batchAddHandler() {
      this.batchFlag = !this.batchFlag
      this.cacheForms = this.validateForm.forms
      this.validateForm.forms.map(item => {
        item.isEdit = true
        const keys = Object.keys(item)
        for (const key of keys) {
          if (key !== 'isEdit') {
            if (key === 'partyPositionList') {
              this.$set(item, key, [])
            } else if (key === 'startDate') {
              this.$set(item, key, this.validateForm.startDate)
            } else if (key === 'endDate') {
              this.$set(item, key, this.validateForm.endDate)
            } else {
              this.$set(item, key, undefined)
            }
          }
        }
      })
      // this.validateForm.forms = []
    },
    deleteHandler(index) {
      this.validateForm.forms.splice(index, 1)
    },
    // 新增席位d
    addHandler() {
      const addBodObj = {
        isEdit: true,
        companyId: this.companyId,
        incumbentType: 'lr',
        partyPositionList: [],
        startDate: this.validateForm.startDate,
        endDate: this.validateForm.endDate
      }
      this.validateForm.forms.push(addBodObj)
    },
    cancelHandle() {
      this.batchFlag = !this.batchFlag
      // validateForm.forms=cacheForms
      this.validateForm.forms.map(item => {
        item.isEdit = false
      })
    },
    // 批量保存
    batchSaveHandler() {
      for (let i = 0; i < this.validateForm.forms.length; i++) {
        this.validateForm.forms[i]['seatIndex'] = i + 1
      }
      const submitData = {
        companyId: this.companyId,
        startDate: this.validateForm.startDate,
        endDate: this.validateForm.endDate,
        dsBodList: this.validateForm.forms
      }

      this.$refs['form'].validate(valid => {
        if (valid) {
          batchSaveBod(submitData).then(res => {
              if (res.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.getList()
              } else {
                this.msgError(res.msg)
              }
              this.batchFlag = !this.batchFlag
            })
        } else {
          this.locationError(document)
        }
      })
    },
    recordHandler(index) {
      // index就是席位信息
      const submitData = {
        companyId: this.companyId,
        seatIndex: index + 1,
        isRecord: '0'
      }
      this.seatLoading = true
      this.seatFormOpen = true
      findDsBySeatIndex(submitData).then(res => {
        this.dsDataList = []
        this.dsDataList = res.data
        this.seatLoading = false
      })
    },
    // 查看外部批披露信息
    seeVEOI() {
        this.VEOIFormOpen = true
        this.VEOILoading = true
        findVEOI(this.companyId).then(res => {
            this.VEOIDataList = res.data
            this.VEOILoading = false
        })
    },
      toUpperCaseAndJoin(positions) {
        return positions.map(position => position.toUpperCase()).join(', ')
      },
    downloadHandler() {
      this.$confirm(this.$t('是否导出Excel?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        const queryParams = { companyId: this.companyId }
        this.downLoadExcelPost('/bod/dsBod/exportBod', queryParams).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t(response.msg))
          } else {
            this.msgError(this.$t(response.msg))
          }
        })
      }).catch(() => {})
    },
    // 下载简历
    downloadFileById(resumeId) {
      if (resumeId) {
          const iframe = document.createElement('iframe')
          iframe.style.display = 'none'
          iframe.style.height = 0
          iframe.src = config.baseURL + '/file/fileBase/common/download?id=' + resumeId + '&Authorization=' + getToken()
          // 与前两种方式不同，iframe需要挂载到页面上才能触发请求
          document.body.appendChild(iframe)
          setTimeout(() => {
            iframe.remove()
          }, 1000)
      } else {
        this.msgError(this.$t('没有附件'))
      }
    },
      // 预览附件
    onlinePreview(rowId) {
      this.$refs.OnlinePreview.onlinePreviewFile(rowId)
    },
    handleSuccess(res, file, index) {
      this.validateForm.forms[index]['sdpFileId'] = file.fileId
      this.validateForm.forms[index]['sdpFileName'] = file.fileName
      this.$forceUpdate()
    },
    handleCdaFileSuccess(res, file, index) {
      this.validateForm.forms[index]['cdaFileId'] = file.fileId
      this.validateForm.forms[index]['cdaFileName'] = file.fileName
      this.$forceUpdate()
    },
    handlelayoffSdpFileSuccess(res, file, index) {
      this.validateForm.forms[index]['layoffSdpFileId'] = file.fileId
      this.validateForm.forms[index]['layoffSdpFileName'] = file.fileName
      this.$forceUpdate()
    },
    handlelayoffCdaFileIdFileSuccess(res, file, index) {
      this.validateForm.forms[index]['layoffCdaFileId'] = file.fileId
      this.validateForm.forms[index]['layoffCdaFileName'] = file.fileName
      this.$forceUpdate()
    },
    handleResumeIdFileSuccess(res, file, index) {
      this.validateForm.forms[index]['resumeId'] = file.fileId
      this.validateForm.forms[index]['resumeName'] = file.fileName
      this.$forceUpdate()
    },
    getShareholdersList() {
      queryShareholdersWithBoardSeats(this.companyId).then(res => {
          this.shareholdersList = res.data
      })
    },
    bodNameChange(index) {
      const row = this.validateForm.forms[index]
      const bodService = this.bodNameOption.find(bod => bod.id === row.bodName)
        if (bodService) {
          this.validateForm.forms[index].gender = bodService.gender
          this.validateForm.forms[index].projectedRetirementDate = bodService.estimatedRetirementDate
          this.validateForm.forms[index].idCard = bodService.idNumber
          this.validateForm.forms[index].phone = bodService.phone
        }
    },
    changeDateStart(val) {
      this.validateForm.forms.map(item => {
        this.$set(item, 'startDate', val)
      })
    },
    changeDateEnd(val) {
      this.validateForm.forms.map(item => {
        this.$set(item, 'endDate', val)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.area-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-flex {
  background: #F7F9FE;
  box-shadow: 0 0 3px 1px #ebeef3;
  margin-bottom: 15px;
  border-radius: 5px;

  .area-header {
    margin: 0;
    padding: 5px 10px;
    border-bottom: 1px solid #ebeef3;

    .area-header-title::before {
      width: 6px;
      height: 6px;
      border-radius: 50%;
    }
  }

  /deep/.flex {
    display: flex;
    border-bottom: 1px solid #ebeef3;

    .el-form-item {
      flex: 1;
      margin: 0;
      border-right: 1px solid #ebeef3;

      .el-form-item__label {
        width: 140px !important;
        max-width: 140px !important;
        text-align: left;
        padding: 5px 10px;
        border-right: 1px solid #ebeef3;
        color: #303133;
        font-weight: 400;
        line-height: normal;
        display: flex;
        align-items: center;
        height: 100%;
        white-space: normal;
      }

      .field {
        height: 100%;
        display: flex;
        align-items: center;
      }

      .el-form-item__content {
        padding: 5px 10px;
        background: #fff;
        line-height: normal;
        height: 100%;
        margin-left: 140px !important;

        .el-select,
        .el-date-editor {
          width: 100%;
        }
      }
    }
  }
}

.left-right {
  justify-content: space-between;
}
.pre {
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-all;
  display: -webkit-box;
}
</style>
